package com.ucode.hrm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ucode.hrm.mapper.HrmPaySlipMapper;
import com.ucode.hrm.service.HrmPaySlipService;
import com.ucode.model.hrm.HrmPaySlip;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class HrmPaySlipServiceImpl implements HrmPaySlipService {

    @Resource
    private HrmPaySlipMapper hrmPaySlipMapper;

    @Resource
    SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public HrmPaySlipMapper initMapper() {
        return hrmPaySlipMapper;
    }

    @Override
    public void setPaySlipShowColumns(List<String> showColumns) {
        stringRedisTemplate.opsForValue().set(PAY_SLIP_SHOW_COLUMNS, JSONUtil.toJsonStr(showColumns));
    }

    @Override
    public List<String> getPaySlipShowColumns() {
        String data = stringRedisTemplate.opsForValue().get("hrm:pay-slip:show-columns");
        List<String> showColumns = StrUtil.isNotBlank(data) ? JSONUtil.toList(data, String.class) : new ArrayList<>();
        return showColumns;
    }

    @Override
    public int batchInsert(List<HrmPaySlip> list) {
        int i = 0;
        if(CollUtil.isNotEmpty( list)) {
            //如果自动提交设置为true,将无法控制提交的条数，改为最后统一提交
            SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
            HrmPaySlipMapper batchMapper = sqlSession.getMapper(HrmPaySlipMapper.class);
            int BATCH = 500;
            for (int index = 0; index < list.size(); index++) {
                batchMapper.insert(list.get(index));
                if (index != 0 && index % BATCH == 0) {
                    sqlSession .commit();
                }
            }
            sqlSession.commit();
        }
        return i;
    }

    @Override
    public int updateVisibleByIds(Collection<Long> ids, Boolean visible) {
        return hrmPaySlipMapper.updateVisibleByIds(ids, visible);
    }
}
